package fun.huixi.weiju.security.handler;

import fun.huixi.weiju.config.JwtConfig;
import fun.huixi.weiju.pojo.entity.WjUser;
import fun.huixi.weiju.pojo.vo.user.UserTokenVO;
import fun.huixi.weiju.service.WjUserService;
import fun.huixi.weiju.util.JwtTokenUtil;
import fun.huixi.weiju.util.ResultUtil;
import fun.huixi.weiju.util.wrapper.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 登录成功处理类
 * @Author Sans
 * @CreateTime 2019/10/3 9:13
 */
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private WjUserService wjUserService;

    /**
     * 登录成功返回结果
     * @Author Sans
     * @CreateTime 2019/10/3 9:27
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        // 组装JWT
        WjUser wjUser =  (WjUser) authentication.getPrincipal();

        UserTokenVO userTokenVO = wjUserService.queryUserTokenInfo(wjUser.getUserId());

        String token = JwtTokenUtil.createAccessToken(userTokenVO);
        token = JwtConfig.tokenPrefix + token;

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", token);
        map.put("user", userTokenVO);

        ResultUtil.responseJson(response, ResultData.ok(map));


    }


}
